import copy
from data_init import initGraph, initLibrary, initPoint
import utils

# 数据初始化
G = initGraph()
librarys = initLibrary()
points = initPoint()
#
# pos = nx.spring_layout(G)
# plt.figure(num=1, figsize=(10, 8))
# nx.draw_networkx(G, pos, node_size=100, font_size=7)
# labels = nx.get_edge_attributes(G, 'weight')
# nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, font_size=7)
# plt.show()

# 计算所有点需求量总和
requestSum = sum(list(map(lambda x: x.request, points)))
# 计算容量总量
capacitySum = sum(list(map(lambda x: x.capacity, librarys)))

Ftotal = 100  # 总建设成本
Atotal = 30  # 总经营成本

print(f">>> {len(points)}个需求点的需求总量为{requestSum}")
print(f">>> {len(librarys)}个仓的容量总量为{capacitySum}")
# 选仓
print(">>> 选择仓的结果如下》》》》》》》》》》》》》》》》》》》》》》")
print()
index = 0
scheme = {}
for n in range(1, len(librarys) + 1):
    # 获取所有选仓组合
    select = utils.combine(librarys, n)
    # 遍历每一种选仓组合
    for objList in select:
        # 计算 所有仓的  总容量，总建设费用，总经营费用
        obj_sum = sum(list(map(lambda x: x.capacity, objList)))
        Fsum = sum(list(map(lambda x: x.construct_cost, objList)))
        Asum = sum(list(map(lambda x: x.operat_cost, objList)))

        # 根据库房和点的总需求量，以及总建设费用  进行方案过滤
        if obj_sum < requestSum or Fsum > Ftotal or Asum > Atotal:
            continue
        # 复制仓方案，用于计算
        obj = copy.deepcopy(objList)
        index += 1
        print(f">>>方案{index},选取{len(obj)}个仓,容量:{obj_sum}->{obj}")
        # 计算每个点到每个仓的最短距离
        minPathMap = utils.veryOneShortestTime(obj, points, G)
        # print(f"最短路径:{minPathMap}")

        # 在次方案下，点与仓绑定
        try:
            utils.pointBind(minPathMap, points, obj)
        except Exception as ex:
            print(">>>异常", ex)
            continue
        print(">>>点绑定仓的结果为:")
        # 遍历每个仓与其绑定的点
        all_path_result = 0  # 统计所有仓遍历对应点的运输成本
        for x in obj:
            print(f">>>{x}")
            library = x.id

            # if index == 3:  # 只输出方案3的路径计算结果
            #     print(f"  >>>路径计算结果: {utils.optimalPath(library, list(map(lambda x: x.id, x.points)), G)}")

            path_result = utils.optimalPath(library, list(map(lambda x: x.id, x.points)), G)
            print(f"  >>> 路径计算结果: {path_result}")
            all_path_result += path_result[0]

        # 计算成本
        costMap = utils.allCost(obj, points, minPathMap, all_path_result)
        scheme[f"方案{index}"] = costMap
        print(f"》》》此方案最终目标成本是{costMap}")
        print()
        # 显示
        # if index == 3:
        #     utils.show(f"方案{index}", copy.deepcopy(G), [library.id for library in obj])

# 方案结果汇总
print(">>> 方案结果汇总 》》》")
for k, v in scheme.items():
    print(f">>> {k}  {v}")

print()
